
require("base")
local print = print
local msg2string = prettytostring
local loadstring = loadstring
local type = type
local task = require"task"
local assert = assert

module("taskmsg")

local function string2msg(s)
    if s then
        local f = loadstring("local t = "..s.." return t")
        return f()
    end
end

function post(ta,msg)
    if type(ta)=="string" then
        ta = task.find(ta)
    end
    assert(type(ta)=="number")
    if type(msg)=="table" then
        msg = msg2string(msg)
    end
    assert(type(msg)=="string")
    local rc = task.post(ta,msg,0)
    assert(rc==0)
    return rc
end

function receive(timeout)
    local msg, flags, rc = task.receive(timeout)
    if msg then
        return string2msg(msg)
    end
end

--[[
msg type list:

    SEARCH_CONNECTED_COM_REQ
    {
        from --task id
    }
    SEARCH_CONNECTED_COM_CNF
    {
        port -- nil means can not detect any phone
    }
    
    AT_CMD_REQ
    {
        at_type -- should be a function name in atcmd.lua
        at_cmd -- what atworker should send to phone
        from -- task id,will be used when AT_CMD_CNF send back
        pause_detector --optional, in some situation,we should make the detector pause
                    -- "true": will cause the detector do not send "AT\n" to phone,
                    -- "false": will restart the detector
                    -- "nil": do nothing with the detector
        timeout --optional,default is 800(ms)
    }
    AT_CMD_CNF
    {
        at_type
        reply
    }
--]]

function test()
    s = 
[[{
    ["msgtype"] = "SEARCH_CONNECTED_COM_REQ",
}]]
    print(s)
    t = string2msg(s)
    print(t)
    print(type(t))
end

--test()
